<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="$router.go(-1)"></i>
      <p>商家注册</p>
    </header>
    
    <!-- 主要内容区域（可滚动） -->
    <div class="scrollable-content">
      <!-- 步骤指示器 -->
      <div class="steps-container">
        <div class="step" :class="{ 'active': currentStep === 1 }">
          <div class="step-circle">
            <div class="step-number">1</div>
          </div>
          <div class="step-label">身份验证</div>
        </div>
        <div class="step-line" :class="{ 'active-line': currentStep === 2 }"></div>
        <div class="step" :class="{ 'active': currentStep === 2 }">
          <div class="step-circle">
            <div class="step-number">2</div>
          </div>
          <div class="step-label">门店信息</div>
        </div>
      </div>
      
      <!-- 步骤1：用户登录 -->
      <div v-if="currentStep === 1" class="step-content">
        <div class="form-illustration">
          <i class="fa fa-user-circle"></i>
          <h3>商家身份验证</h3>
          <p>请使用您的账号登录以验证身份</p>
        </div>
        <ul class="form-box">
          <li>
            <div class="input-container">
              <i class="fa fa-mobile input-icon"></i>
              <input
                type="text"
                v-model="loginData.phoneNumber"
                placeholder="请输入手机号码"
                class="styled-input"
              />
            </div>
          </li>
          <li>
            <div class="input-container">
              <i class="fa fa-lock input-icon"></i>
              <input 
                type="password" 
                v-model="loginData.password" 
                placeholder="请输入密码" 
                class="styled-input"
              />
            </div>
          </li>
        </ul>
        
        <div class="button-action">
          <button @click="userLogin" class="primary-button">
            <i class="fa fa-check-circle"></i> 验证身份
          </button>
        </div>
      </div>
      
      <!-- 步骤2：店铺信息 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="form-illustration">
          <i class="fa fa-store"></i>
          <h3>填写门店信息</h3>
          <p>请填写您的商家信息以完成注册</p>
        </div>
        <ul class="form-box">
          <li>
            <div class="input-container">
              <i class="fa fa-shopping-bag input-icon"></i>
              <input type="text" v-model="business.businessName" placeholder="请输入门店名称" class="styled-input" />
            </div>
          </li>
          <li>
            <div class="input-container">
              <i class="fa fa-map-marker input-icon"></i>
              <input type="text" v-model="business.businessAddress" placeholder="请输入门店详细地址" class="styled-input" />
            </div>
          </li>
          <li>
            <div class="input-container">
              <i class="fa fa-info-circle input-icon"></i>
              <input type="text" v-model="business.businessExplain" placeholder="请输入门店介绍" class="styled-input" />
            </div>
          </li>
          <li>
            <div class="input-container">
              <i class="fa fa-credit-card input-icon"></i>
              <input
                type="number"
                v-model="business.startPrice"
                placeholder="请输入起送费金额"
                min="0"
                step="0.01"
                class="styled-input"
              />
            </div>
          </li>
          <li>
            <div class="input-container">
              <i class="fa fa-truck input-icon"></i>
              <input
                type="number"
                v-model="business.deliveryPrice"
                placeholder="请输入配送费金额"
                min="0"
                step="0.01"
                class="styled-input"
              />
            </div>
          </li>
        </ul>
        
        <div class="button-action">
          <button @click="registerBusiness" class="primary-button">
            <i class="fa fa-check-circle"></i> 提交门店信息
          </button>
        </div>
      </div>
    </div>

    <Footer></Footer>
  </div>
</template>

<script setup>
import Footer from "../components/Footer.vue";
import { useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import axios from 'axios';
import { userApi } from "@/api";

const router = useRouter();
const currentStep = ref(1);
const userId = ref(null);
const userInfo = ref(null);

const loginData = ref({
  phoneNumber: "",
  password: ""
});

const business = ref({
  businessName: "",
  businessAddress: "",
  businessExplain: "",
  startPrice: "",
  deliveryPrice: ""
});

// 用户登录
const userLogin = async () => {
  // 表单验证
  if (!loginData.value.phoneNumber) {
    alert("手机号不能为空！");
    return;
  }
  
  if (!/^\d{11}$/.test(loginData.value.phoneNumber)) {
    alert("请输入有效的11位手机号！");
    return;
  }
  
  if (!loginData.value.password) {
    alert("密码不能为空！");
    return;
  }
  
  try {
    // 调用登录API
    const response = await userApi.login(loginData.value.phoneNumber, loginData.value.password);
    
    console.log("登录响应:", response);
    
    // 提取JWT token
    let jwtToken;
    if (typeof response === 'object' && response !== null) {
      jwtToken = response.id_token || response.token || response.access_token;
    } else if (typeof response === 'string') {
      jwtToken = response;
    }
    
    if (!jwtToken) {
      throw new Error('登录成功但未获取到有效令牌');
    }
    
    // 保存token到localStorage
    localStorage.setItem('jwt-token', jwtToken);
    
    // 获取当前登录用户信息
    const userResponse = await userApi.getCurrentUser();
    console.log("用户信息:", userResponse);
    
    // 保存用户信息
    userInfo.value = userResponse;
    userId.value = userResponse.id;
    localStorage.setItem('user-info', JSON.stringify(userResponse));
    
    // 进入第二步：填写商家信息
    currentStep.value = 2;
    
  } catch (error) {
    console.error("登录失败:", error);
    alert("登录失败: " + (error.response?.data?.message || error.message || "账号或密码错误"));
  }
};

// 注册商家店铺
const registerBusiness = async () => {
  // 验证店铺信息
  if (!business.value.businessName) {
    alert("门店名称不能为空！");
    return;
  }
  
  if (!business.value.businessAddress) {
    alert("门店地址不能为空！");
    return;
  }
  
  if (!business.value.businessExplain) {
    alert("门店介绍不能为空！");
    return;
  }
  
  if (!business.value.startPrice || parseFloat(business.value.startPrice) < 0) {
    alert("起送费必须大于等于0！");
    return;
  }
  
  if (!business.value.deliveryPrice || parseFloat(business.value.deliveryPrice) < 0) {
    alert("配送费必须大于等于0！");
    return;
  }

  try {
    if (!userId.value) {
      // 如果没有userId，尝试从localStorage获取用户信息
      const storedUserInfo = JSON.parse(localStorage.getItem('user-info') || '{}');
      userId.value = storedUserInfo.id;
      
      if (!userId.value) {
        throw new Error("未获取到用户ID，请重新登录");
      }
    }
    
    // 获取JWT令牌
    let token = localStorage.getItem('jwt-token');
    if (!token) {
      throw new Error("未找到认证令牌，请重新登录");
    }
    
    // 检查当前用户是否具有BUSINESS角色，如果没有，先添加角色
    const userWithAuthorities = userInfo.value || JSON.parse(localStorage.getItem('user-info') || '{}');
    const hasBussinessRole = userWithAuthorities.authorities?.some(
      auth => auth.name === "BUSINESS" || auth.name === "ROLE_BUSINESS"
    );
    
    if (!hasBussinessRole) {
      console.log("用户没有商家角色，需要添加商家角色");
      
      try {
        // 调用添加商家角色的API
        const addRoleResponse = await axios.post(`/api/users/${userId.value}/roles/business`, {}, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        console.log("添加商家角色响应:", addRoleResponse);
        
        // 刷新用户信息，获取更新后的权限
        const refreshedUser = await userApi.getCurrentUser();
        userInfo.value = refreshedUser;
        console.log("更新用户权限后的用户信息:", refreshedUser);
        
        // 检查是否成功添加了商家角色
        const hasRoleNow = refreshedUser.authorities?.some(
          auth => auth.name === "BUSINESS" || auth.name === "ROLE_BUSINESS"
        );
        
        if (!hasRoleNow) {
          throw new Error("添加商家角色失败，请联系管理员");
        }
        
        // 添加商家角色后需要重新登录获取包含新权限的JWT令牌
        console.log("重新登录以获取包含新权限的令牌...");
        const reloginResponse = await userApi.login(loginData.value.phoneNumber, loginData.value.password);
        
        // 提取新的JWT token
        let newJwtToken;
        if (typeof reloginResponse === 'object' && reloginResponse !== null) {
          newJwtToken = reloginResponse.id_token || reloginResponse.token || reloginResponse.access_token;
        } else if (typeof reloginResponse === 'string') {
          newJwtToken = reloginResponse;
        }
        
        if (!newJwtToken) {
          throw new Error('重新登录成功但未获取到有效令牌');
        }
        
        // 更新localStorage中的JWT令牌
        localStorage.setItem('jwt-token', newJwtToken);
        console.log("已更新JWT令牌，包含最新权限");
        
        // 使用新的令牌
        token = newJwtToken;
      } catch (error) {
        console.error("添加商家角色或重新登录失败:", error);
        throw new Error("添加商家角色失败: " + (error.message || "请联系管理员"));
      }
    }
    
    // 创建商家信息
    const businessData = {
      businessOwner: {
        id: userId.value
      },
      businessName: business.value.businessName,
      businessAddress: business.value.businessAddress,
      businessExplain: business.value.businessExplain,
      startPrice: parseFloat(business.value.startPrice),
      deliveryPrice: parseFloat(business.value.deliveryPrice),
      remarks: ""
    };
    
    console.log("提交商家信息数据:", businessData);
    
    // 直接使用axios并显式设置Authorization头
    const businessResponse = await axios.post('/api/businesses', businessData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    console.log("商家注册响应:", businessResponse);
    
    // 修复判断逻辑，正确处理嵌套数据结构
    if (businessResponse && businessResponse.data) {
      let businessData = businessResponse.data;
      
      // 检查是否是HttpResult包装的响应格式
      if (businessData.success === true && businessData.data) {
        businessData = businessData.data;
      }
      
      console.log("提取的商家数据:", businessData);
      
      if (businessData && businessData.id) {
        alert("门店注册成功！即将前往商家管理中心。");
        // 保存商家信息
        localStorage.setItem("business", JSON.stringify(businessData));
        // 清除跳转标记
        localStorage.removeItem('skip_to_step_two');
        router.push({ path: "/businessManage" });
      } else {
        throw new Error("无法获取有效的门店ID");
      }
    } else {
      throw new Error("门店信息创建失败");
    }
  } catch (error) {
    console.error("注册请求出错:", error);
    if (error.response && error.response.data) {
      alert("门店注册失败: " + (error.response.data.message || error.response.data));
    } else {
      alert("门店注册失败: " + (error.message || "请检查网络连接"));
    }
  }
};

// 页面初始化
onMounted(() => {
  // 从localStorage获取用户信息
  const storedUserInfo = JSON.parse(localStorage.getItem('user-info') || '{}');
  
  // 检查用户是否已登录且有存储的信息
  if (storedUserInfo && storedUserInfo.id) {
    console.log('找到已存储的用户信息:', storedUserInfo);
    userInfo.value = storedUserInfo;
    userId.value = storedUserInfo.id;
    
    // 检查用户是否已有BUSINESS权限
    const hasBussinessRole = storedUserInfo.authorities?.some(
      auth => auth.name === "BUSINESS" || auth.name === "ROLE_BUSINESS"
    );
    
    // 检查是否需要直接跳转到第二步（只有在用户具有BUSINESS权限时才允许）
    const skipToStepTwo = localStorage.getItem('skip_to_step_two') === 'true';
    
    if (hasBussinessRole && skipToStepTwo) {
      console.log('用户已有BUSINESS权限，直接进入第二步：门店信息填写');
      currentStep.value = 2;
    } else {
      console.log('用户需要完成身份验证步骤');
      currentStep.value = 1;
      // 如果标记存在但用户没有权限，清除它
      if (skipToStepTwo) {
        localStorage.removeItem('skip_to_step_two');
      }
    }
  } else {
    // 如果没有用户信息，重置标记
    localStorage.removeItem('skip_to_step_two');
    console.log('未找到已存储的用户信息，保持在第一步');
    currentStep.value = 1;
  }
});
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: sticky;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper header .fa-angle-left {
  font-size: 6vw;
  position: absolute;
  left: 4vw;
  cursor: pointer;
}

/* 主要内容区域样式 */
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; /* 优化移动端滚动 */
  padding-bottom: 15vw; /* 为底部导航留出空间 */
}

/* 步骤指示器样式 - 优化后 */
.steps-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4vw 0;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 22vw;
  position: relative;
}

.step-circle {
  width: 8vw;
  height: 8vw;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 2vw;
  border: 2px solid #ddd;
}

.step-number {
  font-size: 4vw;
  color: #999;
  font-weight: bold;
}

.step.active .step-circle {
  background-color: #e6f7ff;
  border-color: #0097ff;
}

.step.active .step-number {
  color: #0097ff;
}

.step-label {
  font-size: 3vw;
  color: #666;
}

.step.active .step-label {
  color: #0097ff;
  font-weight: bold;
}

.step-line {
  flex: 1;
  height: 0.5vw;
  background-color: #ddd;
  margin: 0 1vw;
  max-width: 15vw;
  position: relative;
  top: -2vw;
}

.step-line.active-line {
  background-color: #0097ff;
}

/* 表单内容区美化 */
.step-content {
  background-color: #fff;
  margin: 3vw 3vw 6vw;
  border-radius: 8px;
  padding: 4vw;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.form-illustration {
  text-align: center;
  margin-bottom: 5vw;
  padding-bottom: 4vw;
  border-bottom: 1px solid #f0f0f0;
}

.form-illustration i {
  font-size: 15vw;
  color: #0097ff;
  margin-bottom: 2vw;
}

.form-illustration h3 {
  font-size: 5vw;
  color: #333;
  margin-bottom: 2vw;
}

.form-illustration p {
  font-size: 3.5vw;
  color: #999;
}

/* 表单项美化 */
.form-box {
  width: 100%;
  background-color: #fff;
  padding: 2vw 0;
}

.form-box li {
  box-sizing: border-box;
  padding: 3vw 2vw;
  margin-bottom: 3vw;
  border-bottom: 1px solid #f5f5f5;
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 2vw;
  font-size: 4.5vw;
  color: #0097ff;
}

.styled-input {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  outline: none;
  width: 100%;
  height: 10vw;
  font-size: 3.6vw;
  padding: 0 4vw 0 10vw;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.styled-input:focus {
  border-color: #0097ff;
  background-color: #fff;
  box-shadow: 0 0 0 2px rgba(0, 151, 255, 0.1);
}

/* 按钮样式美化 */
.button-action {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 2vw 2vw;
}

.primary-button {
  width: 100%;
  height: 11vw;
  font-size: 4vw;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(135deg, #0097ff, #0077cc);
  border-radius: 6px;
  border: none;
  outline: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 151, 255, 0.25);
  display: flex;
  justify-content: center;
  align-items: center;
}

.primary-button i {
  margin-right: 2vw;
  font-size: 4.5vw;
}

.primary-button:active {
  transform: scale(0.98);
  background: linear-gradient(135deg, #0077cc, #0069b4);
  box-shadow: 0 2px 6px rgba(0, 151, 255, 0.2);
}

/* 底部导航栏固定样式 */
.wrapper > footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 1000;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .wrapper header {
    height: 50px;
  }
  
  .steps-container {
    padding: 15px 0;
  }
  
  .step-circle {
    width: 30px;
    height: 30px;
  }
  
  .styled-input {
    height: 40px;
    font-size: 14px;
    padding: 0 15px 0 35px;
  }
  
  .input-icon {
    left: 10px;
    font-size: 18px;
  }
  
  .primary-button {
    height: 44px;
    font-size: 16px;
  }
  
  .primary-button i {
    margin-right: 8px;
    font-size: 18px;
  }
  
  .form-illustration i {
    font-size: 60px;
  }
  
  .form-illustration h3 {
    font-size: 20px;
  }
  
  .form-illustration p {
    font-size: 14px;
  }
  
  .scrollable-content {
    padding-bottom: 60px;
  }
}
</style>